package com.conversationboard.validate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.conversationboard.config.Configuration;

/**
 * 
 * Check to make sure no illegal characters included in links inserted into the
 * site.
 * 
 * Remove whitespace characters first, to ensure that browsers that don't do
 * this for you.
 * 
 * @author Keith Watson
 * 
 */

public class InputChecker {

	private static Pattern illegalChars = Pattern.compile(".*([<>`{}\\[\\]]|java.*script|" + Configuration.getInstance().getRoot() + "/Pages/Admin|" + Configuration.getInstance().getRoot() + "/Admin).*", (Pattern.DOTALL | Pattern.CASE_INSENSITIVE));
	//private static Pattern illegalImage = Pattern.compile(".*(" + Configuration.getInstance().getDomainName() + "|Admin.*ControllerServlet).*", (Pattern.DOTALL | Pattern.CASE_INSENSITIVE));
	private static Pattern illegalLink = Pattern.compile(".*(Admin.*ControllerServlet|LogoutControllerServlet).*", (Pattern.DOTALL | Pattern.CASE_INSENSITIVE));
	private static final Pattern unicodeBiDirectionalCodes = Pattern.compile("\\\\u202[a-e]|&#823[4-8];", (Pattern.CASE_INSENSITIVE | Pattern.DOTALL));


	/**
	 * Ensure there's no Javascript embedded in HTML links
	 * 
	 * @param strings the array of strings to check
	 * @return true, if any of them contain Javascript
	 */

	public static void refresh() {
		illegalChars = Pattern.compile(".*([<>`{}\\[\\]]|java.*script|" + Configuration.getInstance().getRoot() + "/Pages/Admin/" + Configuration.getInstance().getRoot() + "/Admin).*", (Pattern.DOTALL | Pattern.CASE_INSENSITIVE));
		//illegalImage = Pattern.compile(".*(" + Configuration.getInstance().getDomainName() + "|Admin.*ControllerServlet).*", (Pattern.DOTALL | Pattern.CASE_INSENSITIVE));
		illegalLink = Pattern.compile(".*(Admin.*ControllerServlet|LogoutControllerServlet).*", (Pattern.DOTALL | Pattern.CASE_INSENSITIVE));
	}


	public static boolean containsIllegalCharacter(String... strings) {

		for (String input : strings) {

			String test = removeWhiteSpace(input);

			if (illegalChars.matcher(test).matches()) {
				return true;
			}
		}

		return false;
	}


	public static boolean containsBiDirectionalCodes(String... strings) {

		for (String input : strings) {

			Matcher matcher = unicodeBiDirectionalCodes.matcher(input);

			if (matcher.find()) {
				return true;
			}
		}

		return false;
	}


	public static boolean imageContainsIllegalPhrase(String input) {

		String test = removeWhiteSpace(input);

//		if (illegalImage.matcher(test).matches()) {
//			return true;
//		}

		if (illegalChars.matcher(test).matches()) {
			return true;
		}

		return false;
	}


	public static boolean containsIllegalLink(String input) {

		String test = removeWhiteSpace(input);

		if (illegalLink.matcher(test).matches()) {
			return true;
		}

		return false;

	}


	private static String removeWhiteSpace(String input) {
		input = input.replace("\n", "");
		input = input.replace("\t", "");
		return input;
	}

}
